<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医生管理</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <style>
        tr {
            vertical-align: middle;
            text-align: center;
        }

        .alert_ {
            display: none;
        }

        h4 {
            margin-bottom: 0;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <!-- 主体区域 -->
    <div class="container mt-5">
        <h4>医生管理</h4>
        <hr>
        <!-- 医生信息 -->
        <div class="mb-3 d-flex justify-content-start">
            <!-- 新增医生信息按钮   -->
            <button id="adddoctor" type="button" class="btn btn-primary mx-3" data-bs-toggle="modal"
                data-bs-target="#staticBackdrop">
                新增医生信息
            </button>
            <!-- 查询 -->
            <form class="row gx-3 gy-2 align-items-center">
                <div class="col-5">
                    <select class="form-select subOption" id="branch-search">
                        <option selected>院区</option>
                        <option value="1">雁塔分院</option>
                        <option value="2">高新分院</option>
                    </select>
                </div>
                <div class="col-sm-4">
                    <label class="visually-hidden" for="specificSizeInputName">姓名</label>
                    <input type="text" class="form-control" id="nameVal" placeholder="姓名">
                </div>
                <div class="col-auto">
                    <input type="button" value="查找" class="btn btn-primary searchbtn">
                </div>
            </form>
        </div>
        <hr>
        <!-- 医生信息列表 -->
        <div>
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">ID</th>
                        <th scope="col">头像</th>
                        <th scope="col">姓名</th>
                        <th scope="col">职称</th>
                        <th scope="col">科室</th>
                        <th scope="col">院区</th>
                        <th scope="col">简介</th>
                        <th scope="col">操作</th>
                    </tr>
                </thead>
                <tbody class="table-group-divider 
                doctor-list">
                    <tr>
                        <th scope="row">1</th>
                        <td><img height="50px" src="/images/tooth.png" alt=""></td>
                        <td>Otto</td>
                        <td>@mdo</td>
                        <td>@mdo</td>
                        <td>@mdo</td>
                        <td>@mdo</td>
                        <td>
                            <button type="button" class="btn btn-primary">编辑</button>
                            <button type="button" class="btn btn-danger">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="alert alert-danger alert_" role="alert">
            有重复！请核对重新输入！
        </div>
    </div>
    <!-- 新增医生信息模态框 -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
        aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5">新增医生信息</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addbook">
                        <div class="mb-3">
                            <input type="text" class="form-control" placeholder="请输入姓名..." id="name-input" required>
                        </div>
                        <div class="mb-3">
                            <select class="form-select " id="title-select">
                                <option value="" selected>请选择职称</option>
                                <option value="1">主任医师</option>
                                <option value="2">副主任医师</option>
                                <option value="3">医师</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <select class="form-select " id="branch-select">
                                <option selected>请选择院区</option>
                                <option value="1">院区1</option>
                                <option value="2">院区2</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <select class="form-select " id="department-select">
                                <option selected value="">请选择科室</option>
                                <option value="1">科室1</option>
                                <option value="2">科室2</option>
                                <option value="3">科室3</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <input type="text" class="form-control" id="introduce-input" placeholder="请输入简介..."
                                required>
                        </div>
                        <div class="mb-3">
                            <div class="input-group">
                                <input type="file" class="form-control" id="inputGroupFile04" placeholder="请上传图片..."
                                    aria-describedby="inputGroupFileAddon04" aria-label="Upload">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="price-input" class="form-label">预览:</label>
                            <img id="preview" width="60" src="" alt="">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary saveBtn" id="savebtn"
                        data-bs-dismiss="modal">保存</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        selectbybranch();
        selectbydepartment();
        select();
        let imgPath = null;
        let status = "add";
        let updateId = null;
        var imgPrefix = "http://localhost:3000";
        // 新增医生信息 
        $('#adddoctor').click(() => {
            status = "add";
            $('#name-input').val('');
            $('#title-select').val('');
            $('#department-select').val('');
            $('#branch-select').val('');
            $('#introduce-input').val('');
            $('#preview').attr("src", '');
        })
        // 上传图片
        $("#inputGroupFile04").change(function () {
            let fd = new FormData();
            fd.append("image", $("#inputGroupFile04")[0].files[0]);
            $.ajax({
                method: "post",
                url: "http://localhost:3000/upload/image",
                data: fd,
                contentType: false,
                processData: false,
                success: function (data) {
                    imgPath = data.path;
                    console.log(data.path)
                    imgPath = imgPath.substring(21).replace(/\\/g, "/");
                    $("#preview").attr("src", data.path);
                    // console.log(imgPath);
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                },
            });
        });

        // 提交按钮
        $('#savebtn').click(() => {
            if (status == 'add') {
                add();
            } else if (status == 'update') {
                imgPath = imgPath == '' ? $('#preview').attr('src') : imgPath;
                update();
            }
        })
        // 新增请求
        function add() {
            $.ajax({
                method: 'post',
                url: 'http://localhost:3000/doctor/add',
                data: {
                    name: $('#name-input').val(),
                    title: $('#title-select option:selected').text(),
                    department_id: $('#department-select').val(),
                    branch_id: $('#branch-select').val(),
                    introduce: $('#introduce-input').val(),
                    img: imgPath,
                },
                success: function (data) {
                    // console.log(data)
                    if (data.code == 0) {
                        // alert(data.msg)
                        select();
                    } else {
                        alert(data.msg)
                    }
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        }

        // 删除
        $('.doctor-list').on('click', 'button:contains(删除)', function () {
            console.log($(this))
            $.ajax({
                method: 'get',
                url: 'http://localhost:3000/doctor/del',
                data:
                    { id: $(this)[0].getAttribute('idx') },
                success: function (data) {
                    if (data.code == 0) {
                        select();
                    } else {
                        alert(data.msg)
                    }
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        })
        // 编辑按钮
        $('.doctor-list').on('click', 'button:contains(编辑)', function () {
            let el = JSON.parse($(this).attr('el'));
            $('#name-input').val(el.name);
            $('#title-select option:selected').text(el.title);
            $('#department-select').val(el.department_id);
            $('#branch-select').val(el.branch_id);
            $('#introduce-input').val(el.introduce);
            $('#preview').attr("src", imgPrefix + el.img);
            imgPath = el.img;
            updateId = el.id;
            status = 'update';
        })
        // 编辑请求
        function update(data) {
            $.ajax({
                method: "post",
                url: "http://localhost:3000/doctor/update",
                data: {
                    id: updateId,
                    name: $('#name-input').val(),
                    title: $('#title-select option:selected').text(),
                    department_id: parseInt($('#department-select').val()),
                    branch_id: parseInt($('#branch-select').val()),
                    introduce: $('#introduce-input').val(),
                    img: imgPath,
                },
                success: function (data) {
                    alert(data.msg);
                    select();
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                },
            });
        }
        //按照院区查询
        $('#branch-search').change(function () {
            let val = $('#branch-search').val();
            $.ajax({
                method: 'get',
                data: { branch_id: val },
                url: 'http://localhost:3000/doctor/selectbranchfromdoctor',
                success: function (data) {
                    console.log(data);
                    if (data.code == 0) {
                        render(data.data)
                    } else {
                        alert('该院区无医生！');
                    }
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        })
        // 按照姓名查询
        $('.searchbtn').click(() => {
            $.ajax({
                method: 'get',
                url: 'http://localhost:3000/doctor/selectbyname',
                data: {
                    "name": $('#nameVal').val(),
                },
                success: function (data) {
                    render(data.data)
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        })
        // 查询所有数据
        function select() {
            $.ajax({
                method: 'get',
                url: 'http://localhost:3000/doctor/select',
                success: function (data) {
                    // console.log(data)
                    render(data.data)
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        }

        // 渲染
        function render(data) {
            let str = ''
            data.forEach((item, index) => {
                str += `
                <tr>
                        <th scope="row">${item.id}</th>
                        <td><img height="50px" src="${imgPrefix}${item.img}" alt=""></td>
                        <td>${item.name}</td>   
                        <td>${item.title}</td>
                        <td>${item.department_name}</td>
                        <td>${item.branch_name}</td>
                        <td>${item.introduce}</td>
                        <td>
                            <button data-bs-toggle="modal" data-bs-target="#staticBackdrop" type="button" class="btn btn-primary" el="${JSON.stringify(item).replace(/"/g, '&quot;')}" >编辑</button>
                            <button type="button" class="btn btn-danger" idx="${item.id}">删除</button>
                        </td>
                    </tr>
                `;
            })
            $('.doctor-list').html(str)
        }


        // 添加医生信息时，选择院区时对应的科室下拉框也随之改变
        $('#branch-select').change(function () {
            $.ajax({
                method: 'get',
                url: 'http://localhost:3000/department/selectdepartmentfrombranch',
                data: {
                    id: $('#branch-select').val(),
                },
                success: function (data) {
                    console.log(data)
                    renderdepartmentOption1(data.data);
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                }
            })
        })
        function renderdepartmentOption1(data) {
            let str = '<option value="" selected>请选择部门</option>';
            data.forEach(item => {
                str += `<option value="${item.id}">${item.name}</option>`
            });
            $("#department-select").html(str);
        }


        // 根据类型查找该种类的所有数据
        // 1----分院
        function selectbybranch() {
            $.ajax({
                method: "get",
                url: "http://localhost:3000/doctor/selectbranch",
                success: function (data) {
                    renderbranchOption(data.data);
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                },
            });
        }
        // 2----科室
        function selectbydepartment() {
            $.ajax({
                method: "get",
                url: "http://localhost:3000/doctor/selectdepartment",
                success: function (data) {
                    renderdepartmentOption(data.data);
                },
                error: function (e) {
                    console.log(JSON.stringify(e));
                },
            });
        }
        // 自动生成下拉菜单
        // 1---分院
        function renderbranchOption(data) {
            let str = '<option value="" selected>请选择院区</option>';
            data.forEach(item => {
                str += `<option value="${item.id}">${item.name}</option>`
            });
            $("#branch-select").html(str);
            $("#branch-search").html(str);
        }
        // 2---科室
        function renderdepartmentOption(data) {
            let str = '<option value="" selected>请选择部门</option>';
            data.forEach(item => {
                str += `<option value="${item.id}">${item.name}</option>`
            });
            $("#department-select").html(str);
        }
    </script>
</body>

</html>